有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

将数据从活动传递到片段时出现java问题

这是我的原始应用程序: enter image description here

当我点击按钮将活动中的数据传递到我的应用程序片段时,我的应用程序会变成这样: enter image description here

我不知道为什么

我给你看我的代码

活动\可滚动\选项卡。XML:

<安卓.support.design.widget.CoordinatorLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:app="http://schemas.安卓.com/apk/res-auto"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:id="@+id/container">

    <安卓.support.design.widget.AppBarLayout
        安卓:layout_width="match_parent"
        安卓:layout_height="wrap_content"
        安卓:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <安卓.support.v7.widget.Toolbar
            安卓:id="@+id/toolbar"
            安卓:layout_width="match_parent"
            安卓:layout_height="?attr/actionBarSize"
            安卓:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
            <LinearLayout
                安卓:layout_width="fill_parent"
                安卓:layout_height="wrap_content"
                安卓:layout_centerInParent="true"
                安卓:layout_marginLeft="20dp"
                安卓:layout_marginRight="20dp"
                安卓:gravity="center"
                安卓:orientation="horizontal" >


            <TextView
                安卓:layout_width="wrap_content"
                安卓:layout_height="wrap_content"
                安卓:text="@string/welcome"
                安卓:textSize="20dp"
                安卓:layout_marginLeft="5dp"
                />

            <TextView
                安卓:id="@+id/name"
                安卓:layout_width="wrap_content"
                安卓:layout_height="wrap_content"
                安卓:padding="10dp"
                安卓:textColor="@color/lbl_name"
                安卓:textSize="24dp"
                安卓:layout_marginLeft="5dp"
                />
        <Button
            安卓:id="@+id/btnLogout"
            安卓:layout_width="122dp"
            安卓:layout_height="wrap_content"
            安卓:layout_marginRight="40dip"
            安卓:background="@color/btn_logut_bg"
            安卓:text="@string/btn_logout"
            安卓:textAllCaps="false"
            安卓:textColor="@color/white"
            安卓:textSize="15dp"
            安卓:layout_marginLeft="5dp"
            安卓:onClick="logoutUser"

            />

            </LinearLayout>
           <!-- <FrameLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
                安卓:id="@+id/azz"
                安卓:layout_width="match_parent"
                安卓:layout_height="match_parent" >
                </FrameLayout>-->
        </安卓.support.v7.widget.Toolbar>

        <安卓.support.design.widget.TabLayout
            安卓:id="@+id/tabs"
            安卓:layout_width="match_parent"
            安卓:layout_height="wrap_content"
            app:tabMode="scrollable"/>
    </安卓.support.design.widget.AppBarLayout>

    <安卓.support.v4.view.ViewPager
        安卓:id="@+id/viewpager"
        安卓:layout_width="match_parent"
        安卓:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" >
 <!--       <fragment
            安卓:id="@+id/details_fragment"
            安卓:layout_width="match_parent"
            安卓:layout_height="match_parent"/>-->
    </安卓.support.v4.view.ViewPager>


</安卓.support.design.widget.CoordinatorLayout>

活动:

public  class ScrollableTabsActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private Button cazzo;
    //private SQLiteHandler db;
    private SessionManager session;
    private TextView txtName;
    private TextView txtEmail;
    int s;
    String intentt="";
    File file;
    Uri filePath;
    ArrayList<Integer> hm=new ArrayList<>();
    String path;
    ArrayList<Planet> planetList=new ArrayList();

    private String myString = "azz";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrollable_tabs);


        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        cazzo = (Button) findViewById(R.id.btnLogout);
        txtName = (TextView) findViewById(R.id.name);
        txtEmail = (TextView) findViewById(R.id.numero_telefonico);





        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        cazzo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                logoutUser();
            }
        });
        //db = new SQLiteHandler(getApplication());


        // session manager
       /* session = new SessionManager(getApplication());

        if (!session.isLoggedIn()) {
            logoutUser();
        }*/

        // Fetching user details from SQLite
 /*       HashMap<String, String> user = db.getUserDetails();

        String name = user.get("name");
        String email = user.get("email");
        String id=user.get("id");


        // Displaying the user details on the screen
        System.out.println(name + email);

        txtName.setText(email);*/

        s = getIntent().getIntExtra("EXTRA_SESSION_ID",0);
        System.out.println("IDDDDDDD" + s);

       // getMyData();
    }



   /* public int getMyData() {
        return s;

    }*/


    private void logoutUser() {
        //session.setLogin(false);

      //  db.deleteUsers();

        // Launching the login activity
       /* Intent intent = new Intent(ScrollableTabsActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();*/
        Intent intent = new Intent();
        intent.setPackage("com.asus.filemanager");
        intent.setType("text/xml");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "LOGOUT"), 1);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        filePath = data.getData();

        path = FilePath.getPath(this, filePath);

        System.out.println("PATH" + path);

        int a=0;
        String status="";
        boolean statuss = false;
        String intenttt= path;

        System.out.println("INTENT:"+intenttt);



        file = new File(intenttt);
        System.out.println("FILE:"+file);

        FileInputStream is = null;
        try {
            is = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = null;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        Document doc = null;
        try {
            doc = dBuilder.parse(is);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Element element = doc.getDocumentElement();
        element.normalize();

        NodeList nList = doc.getElementsByTagName("checkboxes_pizza");

        for (int i = 0; i < nList.getLength(); i++) {
            Node node = nList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element2 = (Element) node;
                //tv1.setText(tv1.getText()+"\nName : " + getValue("name", element2)+"\n");
                String id = getValue("id", element2);
                a = Integer.parseInt(id);
                status = getValue("status", element2);

                statuss= Boolean.parseBoolean(status);

                System.out.println("XML:" + a);

                hm.add(a);

                System.out.println("AZZ:" + hm);





            }

        }

        //getMyData();
        Bundle bundle = new Bundle();
        bundle.putString("params", "My String data");
      /*  MyListFragment myObj = new MyListFragment();
        myObj.setArguments(bundle);*/
        Fragment fragment = new MyListFragment();
        fragment.setArguments(bundle);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.container, fragment);
        transaction.commit();
        System.out.println("PASSATO "+bundle);

    }


    private static String getValue(String tag, Element element) {
        NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
        Node node = nodeList.item(0);
        return node.getNodeValue();
    }



   /* @Override
    protected void onPause() {
        super.onPause();
        logoutUser();
    }*/

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new MyListFragment(), "PIZZE");
        adapter.addFrag(new SixFragment(), "SIX");
        adapter.addFrag(new FiveFragment(), "TAVOLI");
        adapter.addFrag(new ThreeFragment(), "BEVANDE");
        adapter.addFrag(new FourFragment(), "STAMPA");
        adapter.addFrag(new TwoFragment(), "TWO");
        adapter.addFrag(new SevenFragment(), "SEVEN");
        adapter.addFrag(new EightFragment(), "EIGHT");
        adapter.addFrag(new NineFragment(), "NINE");
        adapter.addFrag(new TenFragment(), "TEN");


        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(10);
    }
    /*private void logoutUser() {
        SessionManager session;
        session.setLogin(false);

        db.deleteUsers();

        // Launching the login activity
//      Intent intent = new Intent(MyListFragment.this, LoginActivity.class);
        Intent intent = new Intent(getApplicationContext(), LoginActivity.class);

        startActivity(intent);
        getA.finish();
    }*/


    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }


}

行星适配器:

public class PlanetAdapter extends ArrayAdapter<Planet> implements CompoundButton.OnCheckedChangeListener, View.OnClickListener

{
    private List<Planet> planetList;
    private Context context ;
    ArrayList<Birra> objects;
    public boolean Checked;
    private Integer[] imageId;
    String ciao;
    static PlanetAdapter plAdapter;
    String selState ;
    boolean[] itemChecked;
     ArrayList<Integer> hmmm;
    //MyListner mListener;


    public PlanetAdapter(List<Planet> planetList, Context context,Integer[] imageId,ArrayList<Integer> hm) {
        super(context, R.layout.single_listview_item,planetList);
        //itemChecked = new boolean[planetList.size()];

        this.planetList = planetList;
        this.context = context;
        this.imageId = imageId;
        this.itemChecked=new boolean[planetList.size()];
        this.hmmm=hm;
       // mListener=(MyListner)context;


    }
    public PlanetAdapter(@NonNull Context context, @LayoutRes int resource,ArrayList<Integer> a) {
        super(context, resource);
        this.hmmm=a;
        System.out.println("ARRAYLIST2:"+hmmm);

    }


  /*  public void setItems(ArrayList<Integer> items) {
        hmmm = items;
        notifyDataSetChanged();

        //System.out.println("HMMM:"+hmmm);

    }*/





    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    }

    @Override
    public void onClick(View v) {

    }



    public class PlanetHolder {
        public TextView planetName;
        public TextView distView;
        public TextView valuta;
        public CheckBox chkBox;
      //  public EditText edit;
        public TextView caratteristica;
        public TextView id;
        public ImageView imageView;
        public Spinner spinner;
        public NumberPicker np;


    }


    @Override
    public int getCount() {
        return planetList.size();
    }

    @Override
    public Planet getItem(int position) {
        return planetList.get(position);
    }


   // static ArrayList<Integer> itemss;






    @Override
    public View getView(final int position, final View convertView, final ViewGroup parent) {

        View row = convertView;
        PlanetHolder holder = null;



        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(R.layout.single_listview_item, parent, false);
            holder = new PlanetHolder();
            holder.planetName = (TextView) row.findViewById(R.id.name);
            holder.distView = (TextView) row.findViewById(R.id.dist);
            holder.valuta = (TextView) row.findViewById(R.id.valuta);
            holder.chkBox = (CheckBox) row.findViewById(R.id.chk_box);
            holder.spinner = (Spinner) row.findViewById(R.id.simpleSpinner);
            holder.np=(NumberPicker)row.findViewById(R.id.np);
           // iterator.setOnClickListener(this.PlanetHolder);
            holder.caratteristica=(TextView) row.findViewById(R.id.caratteristica);
            holder.imageView = (ImageView) row.findViewById(R.id.ivImage);
            holder.spinner.setVisibility(View.GONE);


            // holder.id = (TextView) row.findViewById(R.id.id);


            row.setTag(holder);

        } else {
            holder = (PlanetHolder) row.getTag();


        }



        final Planet p = planetList.get(position);
        System.out.println("stampato P" + p);
        holder.imageView.setImageResource(imageId[position]);
        holder.planetName.setText(p.getName());
        holder.distView.setText("" + p.getDistance());
        holder.valuta.setText("" + p.getValuta());
        holder.chkBox.setChecked(p.isSelected());
        holder.chkBox.setTag(p);
        holder.caratteristica.setText(p.getCaratteristica());


        SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
        boolean isChecked = states.getBoolean("holder.chkBox" + holder.planetName.getText().toString(), false);
        System.out.println(isChecked);




        if (isChecked) {



            holder.spinner.setVisibility(View.VISIBLE);
            holder.np.setVisibility(View.VISIBLE);







        } else {
            holder.chkBox.setChecked(false);
            holder.spinner.setVisibility(View.GONE);
            holder.np.setVisibility(View.GONE);

         }


        holder.chkBox.setOnCheckedChangeListener(PlanetAdapter.this);



        final PlanetHolder finalHolder = holder;
        Planet z=getItem(position);
        System.out.println(z);










        holder.chkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (finalHolder.chkBox.isChecked()) {

                itemChecked[position]=true;

                    System.out.println("POSITION:"+position);
                    finalHolder.spinner.setVisibility(View.VISIBLE);
                    finalHolder.np.setVisibility(View.VISIBLE);
                    finalHolder.np.setMaxValue(10);
                    finalHolder.np.setMinValue(0);
                    finalHolder.np.setWrapSelectorWheel(true);

                    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                            getContext(),
                            R.array.country_arrays,
                            安卓.R.layout.simple_spinner_item);
                    adapter.setDropDownViewResource(安卓.R.layout.simple_spinner_dropdown_item);
                    finalHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            finalHolder.spinner.setSelection(position);
                          //  selState = finalHolder.spinner.getSelectedItem().toString();
                         //   p.setQuantità(finalHolder.edit.getText().toString().trim());
                            p.setTipo(finalHolder.spinner.getSelectedItem().toString());

                            System.out.println("p.getTipo()"+p.getTipo());





                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }


                    });
                    finalHolder.np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                        @Override
                        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                            p.setQuantità2(newVal);
                            System.out.println(p.getQuantità2());
                            SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = states.edit();
                            editor.putInt("finalHolder.picker" + finalHolder.planetName.getText().toString(), finalHolder.np.getId());
                            editor.commit();
                        }
                    });



                    SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = states.edit();
                    editor.putBoolean("holder.chkBox" + finalHolder.planetName.getText().toString(), true);
                    editor.commit();



                } else {
                    finalHolder.spinner.setVisibility(View.GONE);
                    finalHolder.np.setVisibility(View.GONE);
                    finalHolder.np.setValue(0);


                }

            }
        });




        return row;
    }




    }

单个\u列表视图\u项。XML

<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:layout_width="match_parent"
    安卓:layout_height="wrap_content"
    安卓:orientation="horizontal" >

    <CheckBox 
        安卓:id="@+id/chk_box"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:layout_alignParentLeft="true" />
    <LinearLayout
        安卓:id="@+id/linearLayout1"
        安卓:layout_width="0dp"
        安卓:layout_height="wrap_content"
        安卓:layout_marginLeft="5dp"
        安卓:orientation="vertical"
        安卓:layout_weight="1" >

    <TextView
        安卓:id="@+id/name"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:layout_toRightOf="@id/chk_box"
        安卓:textStyle="bold"
        安卓:textColor="#000000" />
        <LinearLayout
            安卓:layout_width="match_parent"
            安卓:layout_height="match_parent">

            <TextView
                安卓:id="@+id/caratteristica"
                安卓:layout_width="wrap_content"
                安卓:layout_height="wrap_content"
                安卓:layout_below="@id/name"
                安卓:layout_toRightOf="@id/chk_box"
                安卓:textStyle="italic" />
        </LinearLayout>


    <LinearLayout
        安卓:layout_width="match_parent"
        安卓:layout_height="match_parent">
    <TextView
        安卓:id="@+id/dist"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:layout_below="@id/caratteristica"
        安卓:layout_toRightOf="@id/chk_box"
        安卓:textSize="12sp"
        安卓:textStyle="italic" />
        <TextView
            安卓:id="@+id/valuta"
            安卓:layout_width="wrap_content"
            安卓:layout_height="wrap_content"
            安卓:layout_marginLeft="5dp"
            安卓:textSize="12sp"
            安卓:textStyle="italic" />
    </LinearLayout>

        <Spinner
            安卓:id="@+id/simpleSpinner"
            安卓:layout_width="wrap_content"
            安卓:layout_height="wrap_content"
            安卓:layout_centerHorizontal="true"
            安卓:layout_marginTop="50dp"
            安卓:entries="@array/country_arrays"/>

        <NumberPicker
            安卓:id="@+id/np"
            安卓:layout_width="wrap_content"
            安卓:layout_height="wrap_content"
            />

    </LinearLayout>
    <ImageView
        安卓:id="@+id/ivImage"
        安卓:layout_width="72dp"
        安卓:layout_height="72dp"
        安卓:layout_marginRight="5dp"
        安卓:layout_gravity="center"
        />


</LinearLayout>

共 (2) 个答案

  1. # 1 楼答案

    请格式化代码并删除多余的空行。因为它几乎不可读

    不要在onActivityResult中添加片段,而是在onCreate中添加片段,必要时在onActivityResult中设置适配器数据

    所以把这段代码移到onCreate

    Fragment fragment = new MyListFragment();
    fragment.setArguments(bundle);
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.add(R.id.container, fragment);
    transaction.commit();
    

    而且MyListFragment应该有一个名为refreshlist的方法

    此外,在片段布局中,在xml中放置一个白色背景:

    android:background="@android:color/white"
    
  2. # 2 楼答案

    从适配器的getView()方法隐藏并显示SpinnerNumberPicker时出现问题:

    @Override
    public View getView(final int position, final View convertView, final ViewGroup parent) {
    
        ........
        ................
    
        if (isChecked) {
            holder.spinner.setVisibility(View.VISIBLE);
            holder.np.setVisibility(View.VISIBLE);
        } else {
            holder.chkBox.setChecked(false);
            holder.spinner.setVisibility(View.GONE);
            holder.np.setVisibility(View.GONE);
        }
        ........
        ................
    }
    

    似乎您的Listview项的布局设计不正确。更新single_listview_item.xml布局设计如下:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="8dp">
    
        <CheckBox
            android:id="@+id/chk_box"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true" />
    
        <ImageView
            android:id="@+id/ivImage"
            android:layout_width="72dp"
            android:layout_height="72dp" 
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"/>
    
        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_toRightOf="@id/chk_box"
            android:layout_toLeftOf="@id/ivImage"
            android:orientation="vertical">
    
            <TextView
                android:id="@+id/name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/chk_box"
                android:textStyle="bold"
                android:textColor="#000000"
                android:text="This ia name"/>
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
    
                <TextView
                    android:id="@+id/caratteristica"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/name"
                    android:layout_toRightOf="@id/chk_box"
                    android:textStyle="italic"
                    android:text="This is caratteristica"/>
            </LinearLayout>
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:id="@+id/dist"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="12sp"
                    android:textStyle="italic"
                    android:text="10"/>
                <TextView
                    android:id="@+id/valuta"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:textSize="12sp"
                    android:textStyle="italic"
                    android:text="$"/>
            </LinearLayout>
    
            <Spinner
                android:id="@+id/simpleSpinner"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="50dp"
                android:entries="@array/country_arrays"
                android:visibility="visible"/>
    
            <NumberPicker
                android:id="@+id/np"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:visibility="visible"/>
    
        </LinearLayout>
    </RelativeLayout>